package com.example.demo.interceptorToken;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.StreamUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author hulei
 * @date 2024/1/11 19:48
 * 自定义请求拦截器(spring boot 3.0以下的版本,需要继承HandlerInterceptorAdapter类,实现对应得方法)
 */

public class RequestInterceptor implements HandlerInterceptor {

    /**
     * 需要从请求里验证的关键字参数名
     */
    private static final String TOKEN_STR = "token";

    /**
     * 进入拦截的方法前触发
     * 这里主要从打了注解请求中查找有没有token关键字,并且token的值是否符合一定的生成规则,是就放行,不是就拦截
     */
    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        if (handler instanceof HandlerMethod handlerMethod) {
            //获取token注解
            TokenCheck tokenCheck = getTokenCheckAnnotation(handlerMethod);
            //请求参数有form_data的话，防止request.getHeaders()或request.getInputStream()报已使用错误,单独处理
            if (request.getContentType() != null && request.getContentType().contains("multipart/form-data")) {
                //判断当前注解是否存在
                if (tokenCheck != null) {
                    final StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
                    MultipartHttpServletRequest multipartHttpServletRequest = multipartResolver.resolveMultipart(request);
                    String urlOrBodyToken = "", tokenFromHeaders, tokenFromCookies;
                    //获取全部参数,不管是params里的还是body(form_data)里的
                    urlOrBodyToken = getTokenFromUrlOrBody(multipartHttpServletRequest);
                    //从headers获取token
                    tokenFromHeaders = getTokenFromHeaders(multipartHttpServletRequest);
                    //从cookies获取token
                    tokenFromCookies = getTokenFromCookies(multipartHttpServletRequest);
                    if (tokenRuleValidation(urlOrBodyToken) || tokenRuleValidation(tokenFromHeaders) || tokenRuleValidation(tokenFromCookies)) {
                        return true;
                    } else {
                        returnJson(response, "token校验失败");
                        return false;
                    }
                }
            } else {
                //判断当前注解是否存在
                if (tokenCheck != null) {
                    // 获取请求方式,如果需要根据请求方式做不同处理,则获取后自行判断即可
                    //String requestMethod = request.getMethod();
                    request = new RequestWrapper(request);
                    //token关键字,分别是来自url、headers、cookies、body中的token
                    String tokenFromUrl, tokenFromHeaders, tokenFromCookies, tokenFromBody;
                    //url获取token请求参数
                    tokenFromUrl = getTokenFromUrl(request);
                    //从headers获取token
                    tokenFromHeaders = getTokenFromHeaders(request);
                    //从cookies获取token
                    tokenFromCookies = getTokenFromCookies(request);
                    //从body体获取token参数
                    tokenFromBody = getTokenFromBody(request);
                    //token校验判断
                    if (tokenRuleValidation(tokenFromUrl) || tokenRuleValidation(tokenFromHeaders) || tokenRuleValidation(tokenFromCookies) || tokenRuleValidation(tokenFromBody)) {
                        return true;
                    } else {
                        returnJson(response, "token校验失败");
                        return false;
                    }
                }
            }
            return true;
        }
        return true;
    }

    /**
     * 获取TokenCheck注解(先从类上优先获取)
     */
    private TokenCheck getTokenCheckAnnotation(HandlerMethod handler) {
        Method method = handler.getMethod();
        //获取方法所属的类,并获取类上的@TokenCheck注解
        Class<?> clazz = method.getDeclaringClass();
        TokenCheck tokenCheck = null;
        if (clazz.isAnnotationPresent(TokenCheck.class)) {
            tokenCheck = clazz.getAnnotation(TokenCheck.class);
        }
        //类上没有注解,则从方法上再获取@TokenCheck
        tokenCheck = tokenCheck == null ? method.getAnnotation(TokenCheck.class) : tokenCheck;
        return tokenCheck;
    }

//===============================================================================================================================

    /**
     * form_data参数形式,从url和body中获取符合生成规则条的token
     */
    private String getTokenFromUrlOrBody(HttpServletRequest multipartHttpServletRequest) {
        String urlOrBodyToken = "";
        Map<String, String[]> urlAndBodyParam = multipartHttpServletRequest.getParameterMap();
        String[] tokenFromUrlOrBody = urlAndBodyParam.get(TOKEN_STR);
        for (String tokenStr : tokenFromUrlOrBody) {
            if (tokenRuleValidation(tokenStr)) {
                urlOrBodyToken = tokenStr;
                break;
            }
        }
        return urlOrBodyToken;
    }
//===============================================================================================================================

    /**
     * 从headers获取token
     */
    private String getTokenFromHeaders(HttpServletRequest request) {
        Map<String, String> headerMap = new HashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            headerMap.put(name, value);
        }
        return headerMap.get(TOKEN_STR) == null ? "" : String.valueOf(headerMap.get(TOKEN_STR));
    }
//===============================================================================================================================

    /**
     * 从cookies获取token
     */
    private String getTokenFromCookies(HttpServletRequest request) {
        Map<String, String> cookieMap = new ConcurrentHashMap<>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            Arrays.stream(cookies).forEach(element ->
                    cookieMap.put(element.getName(), element.getValue())
            );
        }
        return cookieMap.get(TOKEN_STR) == null ? "" : String.valueOf(cookieMap.get(TOKEN_STR));
    }

//===============================================================================================================================

    /**
     * 从请求体获取token参数
     */
    private String getTokenFromBody(HttpServletRequest request) throws Exception {
        String bodyParamsStr = this.getPostParam(request);
        String tokenFromBody = "";
        //判断是否是json数组
        boolean isJsonArray = JSONUtil.isTypeJSONArray(bodyParamsStr);
        if (!isJsonArray) {
            tokenFromBody = JSONUtil.parseObj(bodyParamsStr).getStr(TOKEN_STR);
        } else {
            JSONArray jsonArray = JSONUtil.parseArray(bodyParamsStr);
            Set<String> tokenSet = new HashSet<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                if (StringUtils.isNotEmpty(jsonObject.getStr(TOKEN_STR))) {
                    tokenSet.add(jsonObject.getStr(TOKEN_STR));
                }
            }
            if (!tokenSet.isEmpty()) {
                tokenFromBody = tokenSet.stream().filter(this::tokenRuleValidation).findFirst().orElse("");
            }
        }
        return tokenFromBody;
    }

    private String getPostParam(HttpServletRequest request) throws Exception {
        RequestWrapper readerWrapper = new RequestWrapper(request);
        return StringUtils.isEmpty(getBodyParams(readerWrapper.getInputStream(), request.getCharacterEncoding())) ?
                "{}" : getBodyParams(readerWrapper.getInputStream(), request.getCharacterEncoding());
    }

    private String getBodyParams(ServletInputStream inputStream, String charset) throws Exception {
        String body = StreamUtils.copyToString(inputStream, Charset.forName(charset));
        if (StringUtils.isEmpty(body)) {
            return "";
        }
        return body;
    }

//===============================================================================================================================

    /**
     * 如果是get请求,则把url中的请求参数获取到,转换为map
     */
    public String getTokenFromUrl(HttpServletRequest request) throws UnsupportedEncodingException {
        //获取当前请求的编码方式,用于参数value解码
        String encoding = request.getCharacterEncoding();
        String urlQueryString = request.getQueryString();
        Map<String, String> queryMap = new HashMap<>();
        String[] arrSplit;
        if (urlQueryString == null) {
            return "";
        } else {
            //每个键值为一组
            arrSplit = urlQueryString.split("&");
            for (String strSplit : arrSplit) {
                String[] arrSplitEqual = strSplit.split("=");
                //解析出键值
                if (arrSplitEqual.length > 1) {
                    queryMap.put(arrSplitEqual[0], URLDecoder.decode(arrSplitEqual[1], encoding));
                } else {
                    if (!"".equals(arrSplitEqual[0])) {
                        queryMap.put(arrSplitEqual[0], "");
                    }
                }
            }
        }
        return queryMap.get(TOKEN_STR) == null ? "" : String.valueOf(queryMap.get(TOKEN_STR));
    }

    /**
     * token 规则校验
     *
     * @param token token关键字
     */
    private boolean tokenRuleValidation(String token) {
        return "AAABBB".equals(token);

    }

    /**
     * 离开拦截的方法后触发
     */
    @Override
    public void postHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, ModelAndView modelAndView) {

    }

    /**
     * 返回response的json信息
     */
    private void returnJson(HttpServletResponse response, String json) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(json);
        }
    }
}
